<template>
	<view class="content">
		<view class="order-item">
			<view class="order-header">
				<text class="order-id">订单编号：{{orderDetail.orderNumber}}</text>
				<text class="order-status">{{getStatusText(orderDetail.state)}}</text>
			</view>
			<view class="product-info">
				<image :src="orderDetail.orderCommodityDtoList[0].commodityDto.pictureIntegrationDtoS[0].pictureUrl"
					class="product-image"></image>
				<view class="product-details">
					<view class="product-name">{{orderDetail.orderCommodityDtoList[0].commodityDto.commodityName}}
					</view>
					<view class="product-commodity">
						{{orderDetail.orderCommodityDtoList[0].commodityDto.commoditySpecificationBasicInformationDto.attributeName}}:
						{{orderDetail.orderCommodityDtoList[0].commodityDto.commoditySpecificationBasicInformationDto.attributeValue}}
						<span
							v-if="orderDetail.orderCommodityDtoList[0].commodityDto.commoditySpecificationBasicInformationDto.commoditySpecificationAttributeInfoDto &&
									orderDetail.orderCommodityDtoList[0].commodityDto.commoditySpecificationBasicInformationDto.commoditySpecificationAttributeInfoDto.specificationName && 
									orderDetail.orderCommodityDtoList[0].commodityDto.commoditySpecificationBasicInformationDto.commoditySpecificationAttributeInfoDto.specificationValue">
							,{{ orderDetail.orderCommodityDtoList[0].commodityDto.commoditySpecificationBasicInformationDto.commoditySpecificationAttributeInfoDto.specificationName }}:
							{{ orderDetail.orderCommodityDtoList[0].commodityDto.commoditySpecificationBasicInformationDto.commoditySpecificationAttributeInfoDto.specificationValue }}
						</span>
					</view>
					<view class="product-price-specs">
						<text
							class="product-price">￥{{orderDetail.orderCommodityDtoList[0].commodityDto.commoditySpecificationBasicInformationDto.commoditySpecificationAttributeInfoDto.sellingPrice}}</text>
						<text class="product-specs">×{{orderDetail.orderCommodityDtoList[0].bayCount}}</text>
					</view>
					<view class="quantity-total" style="text-align: right;">
						<text>共计{{orderDetail.orderCommodityDtoList[0].bayCount}}件商品,</text>
						<text>合计：￥<text style="color: red;">{{orderDetail.amountActuallyPaid}}</text></text>
					</view>
				</view>
			</view>

		</view>
		<view class="contentBox">
			<p class="leftTitle">商品总价</p>
			<p class="rightContent">￥{{orderDetail.amountActuallyPaid}}</p>
			<p class="leftTitle">订单运费</p>
			<p class="rightContent">￥{{orderDetail.postage}}</p>
			<p class="leftTitle">实付款</p>
			<p class="rightContent">￥{{orderDetail.amountActuallyPaid}}</p>
		</view>
		<view class="contentBox">
			<p class="leftTitle">订单编号</p>
			<p class="rightContent">{{orderDetail.orderNumber}}</p>
			<p class="leftTitle">支付方式</p>
			<p class="rightContent">{{getpayType(orderDetail.payType)}}</p>
			<p class="leftTitle">下单时间</p>
			<p class="rightContent">{{orderDetail.creationTime}}</p>
			<p class="leftTitle">付款时间</p>
			<p class="rightContent">{{orderDetail.lastModificationTime}}</p>
			<p class="leftTitle">收货地址</p>
			<p class="rightContent">{{orderDetail.consigneeAddress}}</p>
		</view>
		<view class="contentBox" v-if="orderDetail.expressCompanyDto">
			<p class="leftTitle">快递公司</p>
			<p class="rightContent">{{orderDetail.expressCompanyDto.logisticsCompanyName || '-'}}</p>
			<p class="leftTitle">快递单号</p>
			<p class="rightContent" @click="copyTrackingNumber">
				{{orderDetail.trackingNumber|| '-'}}
				<span class="copy-icon" style="margin-left: 10rpx;">复制</span> <!-- 可选：添加一个小图标或文字提示 -->
			</p>
		</view>
		<!-- 操作按钮 -->
		<view class="order-actions">
			<view class="button" @click="onDeleteOrder(orderDetail)">删除订单</view>
			<template v-if="orderDetail.state == 0">
				<view class="button" @click="onPayOrder(orderDetail)">支付</view>
				<view class="button" @click="onCancelOrder(orderDetail)">取消订单</view>
			</template>
			<template v-if="orderDetail.state == 4">
				<view class="button" @click="onReceiptOfGoods(orderDetail)">确认收货</view>
			</template>
			<template v-if="orderDetail.state == 6">
				<view class="button" @click="onEvaluate(orderDetail)">去评价</view>
			</template>
		</view>
	</view>
</template>

<script>
	import {
		delOrder,
		cancellOrder,
		editOrder,
		addPayment,
		getOrderDetail
	} from '@/api/order.js';
	import wx from 'jweixin-module';
	export default {
		data() {
			return {
				orderDetail: {},
				orderId:''
			};
		},
		onLoad(options) {
			this.orderId=options.id
			// this.getDetail(options.id)
		},
		onShow() {
			if(this.orderId){
				this.getDetail(this.orderId)
			}
		},
		methods: {
			copyTrackingNumber() {
				const textToCopy = this.orderDetail.trackingNumber;
				uni.setClipboardData({
					data: textToCopy,
					success: function() {
						uni.showToast({
							title: '复制成功',
							icon: 'success'
						});
					},
					fail: function(err) {
						console.error('复制失败', err);
						uni.showToast({
							title: '复制失败，请重试',
							icon: 'none'
						});
					}
				});
			},
			getDetail(id) {
				getOrderDetail(id).then(res => {
					this.orderDetail = res.data
				})
			},
			onPayOrder(order) {
				console.log('支付订单:', order);
				// 假设 addOrder 是一个异步函数，用于创建订单并获取支付参数
				addPayment(order.orderNumber, 1).then(res => {
					console.log(res, "微信支付");
					// 检查 WeixinJSBridge 是否可用
					if (typeof WeixinJSBridge === "undefined") {
						console.error(
							"WeixinJSBridge is not available. Please open this page in WeChat browser.");
						uni.showToast({
							title: '请在微信浏览器中打开此页面',
							icon: 'none',
							duration: 2000
						});
						return;
					}

					// 调用 WeixinJSBridge 进行支付
					WeixinJSBridge.invoke(
						'getBrandWCPayRequest', {
							appId: res.data.appId,
							timeStamp: "" + res.data.timeStamp, // 强制转换为字符串
							nonceStr: res.data.nonceStr,
							package: res.data.packageValue,
							signType: res.data.signType,
							paySign: res.data.paySign
						},
						function(response) {
							console.log(response, "支付回调结果");
							handlePaymentResponse(response);
						}
					);
				}).catch(error => {
					console.error("创建订单失败：", error);
					uni.showToast({
						title: '创建订单失败，请稍后再试',
						icon: 'none',
						duration: 2000
					});
				});

				// 定义处理支付响应的函数
				function handlePaymentResponse(response) {
					if (response.err_msg === "get_brand_wcpay_request:ok") {
						// 支付成功后的处理逻辑
						console.log("支付成功！");
						uni.showToast({
							title: '支付成功',
							icon: 'success',
							duration: 2000
						});
						// 可以在这里添加更多支付成功的逻辑，例如跳转到订单详情页等
						this.getDetail(order.id)
					} else {
						// 支付失败或其他情况的处理逻辑
						console.error("支付失败或用户取消支付：", response.err_msg);
						uni.showToast({
							title: '支付失败或已取消',
							icon: 'none',
							duration: 2000
						});

						// 根据需要可以提供给用户重新尝试支付的机会
					}
				}
				console.log('Submit Order with Data:', data);
			},
			onCancelOrder(order) {
				cancellOrder(order.orderNumber).then(res => {
					uni.showToast({
						icon: "none",
						title: '取消成功'
					});
					uni.navigateBack({
						delta: 1 // 返回的页面数，如果填1，则返回上一级页面
					});
					// this.getDetail(order.id)
				})
			},
			onDeleteOrder(order) {
				console.log('删除订单:', order);
				const data = {
					id: order.id,
					userDeletion: 1
				}
				delOrder(data).then(res => {
					uni.showToast({
						icon: "none",
						title: '删除成功'
					});
					uni.navigateBack({
						delta: 1 // 返回的页面数，如果填1，则返回上一级页面
					});
					// this.getDetail(order.id)
				})
			},
			onEvaluate(order) {
				console.log('去评价:', order);
				uni.navigateTo({
					url: '/pages/my/myOrder/addEvaluate/index?commodityId=' + order.orderCommodityDtoList[0]
						.commodityId + '&orderId=' + order.id
				})
			},
			onReceiptOfGoods(order) {
				console.log('收货:', order);
				const params = {
					...order,
					state: 5
				};
				editOrder(params).then(res => {
					uni.showToast({
						icon: "none",
						title: '收货成功'
					});
					this.pageNumber = 1
					this.orderList = []
					this.getDetail(order.id)
				})
			},
			getStatusText(state) {
				const stateMap = {
					0: '待付款',
					1: '付款超时',
					2: '待发货',
					3: '已取消',
					4: '已发货',
					5: '已收货',
					6: '待评价',
					7: '已评价',
					8: '已完成',
					9: '发起退款申请',
					10: '退款申请通过',
					11: '退款申请驳回'
				};
				return stateMap[state] || '未知状态';
			},
			getpayType(payType) {
				const payTypeMap = {
					0: '微信支付',
					1: '微信支付',
					2: '余额支付',
					3: '余额支付',
					4: '余额充值',
					5: '线下支付',
				};
				return payTypeMap[payType] || '未知状态';
			}
		},

	};
</script>

<style lang="scss">
	@import '@/uni.scss'; // 导入全局 SCSS 变量文件

	.content {
		min-height: 100vh;
		padding: 20rpx;
		background-color: $uni-bg-color-grey;
		position: relative;
	}

	.order-item {
		padding: 20rpx;
		background-color: $uni-bg-color-white;
		border-radius: 20rpx;

		.order-header {
			display: flex;
			justify-content: space-between;
			margin-bottom: 10rpx;

			.order-id,
			.order-status {
				font-size: 28rpx;
			}
		}

		.product-info {
			display: flex;

			.product-image {
				width: 180rpx;
				height: 180rpx;
				margin-right: 20rpx;
			}

			.product-details {
				flex-grow: 1;

				.product-name {
					font-size: 32rpx;
					line-height: 1.5;
					max-height: 96rpx; // 两行的高度
					overflow: hidden;
				}

				.product-commodity {
					font-size: 24rpx;
					color: #777;
				}

				.product-price-specs {
					display: flex;
					justify-content: space-between;
					margin-top: 10rpx;

					.product-price {
						font-weight: bold;
					}

					.product-specs {
						color: #777;
					}
				}

				.quantity-total {
					font-size: 28rpx;
					margin-top: 10rpx;
					color: #777;
				}
			}
		}


	}

	.contentBox {
		padding: 20rpx;
		margin-top: 20rpx;
		background-color: $uni-bg-color-white;
		border-radius: 20rpx;
		display: flex;
		flex-wrap: wrap;
		font-size: 28rpx;

		.leftTitle {
			width: 30%;
			height: 50rpx;
			text-align: left;
		}

		.rightContent {
			width: 70%;
			text-align: right;
		}
	}

	.order-actions {
		width: 100%;
		height: 80rpx;
		line-height: 80rpx;
		text-align: right;
		background-color: white;
		position: fixed;
		bottom: 0;
		left: 0;
		box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.1);
		z-index: 10;
		padding: 20rpx 0rpx;

		.button {
			display: inline-block;
			width: auto;
			height: 60rpx;
			line-height: 60rpx;
			font-size: 28rpx;
			border-radius: 50rpx;
			border: 2rpx solid $uni-border-color;
			padding: 0 30rpx;
			margin-right: 20rpx;
		}
	}
</style>